package com.suke.controller;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.suke.pojo.Employee;
import com.suke.service.EmployeeService;
import com.suke.utils.Msg;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;

/*
 * 控制层：处理器类
 * */
@Controller
public class EmployeeController {

    /*注入Service层对象*/
    @Autowired
    private EmployeeService employeeService;

    /*
     * 查询员工信息的处理方法（分页）
     * */
    @RequestMapping("/emps")
    @ResponseBody
    public Msg getEmps(@RequestParam(value = "pn", defaultValue = "1") Integer pn) {
        //创建分页的工具，不需要关心分页的实现，只需要传入数据
        PageHelper.startPage(pn, 5);
        List<Employee> emps = employeeService.getAll();
        //使用PageInfo对象封装了分页的信息，包括查询的数据，传入的显示的页数
        PageInfo page = new PageInfo(emps, 5);
        return Msg.success().add("pageInfo", page);
    }

    /*新增员工保存的处理方法*/
    @RequestMapping(value = "/emp", method = RequestMethod.POST)
    @ResponseBody
    public Msg saveEmp(Employee employee) {
        employeeService.saveEmp(employee);
        return Msg.success();
    }

    /*获取员工信息的处理器方法*/
    @RequestMapping(value = "/emp/{id}", method = RequestMethod.GET)
    @ResponseBody
    public Msg getEmp(@PathVariable("id") Integer id) {
        Employee employee = employeeService.getEmp(id);
        System.out.println(employee);
        return Msg.success().add("emp", employee);
    }

    /*修改保存用户信息的方法*/
    @RequestMapping(value = "/emp/{empId}", method = RequestMethod.PUT)
    @ResponseBody
    public Msg saveUpdateEmp(Employee employee) {
        employeeService.updateEmp(employee);
        System.out.println(employee);
        return Msg.success();
    }

    /*
     * 将单个删除的处理方法和批量删除合拼
     * */
    @RequestMapping(value = "/emp/{ids}", method = RequestMethod.DELETE)
    @ResponseBody
    public Msg deleteEmps(@PathVariable("ids") String ids) {
        System.out.println(ids);
        //批量操作删除
        if (ids.contains("-")) {
            List<Integer> del_ids = new ArrayList<>();
            String[] str_ids = ids.split("-");
            //将id组装成集合
            for (String str_id : str_ids) {
                del_ids.add(Integer.parseInt(str_id));
            }
            employeeService.deleteEmps(del_ids);
        } else {
            //单个删除
            Integer id = Integer.parseInt(ids);
            employeeService.deleteEmp(id);
        }
        return Msg.success();
    }
}